<template>
  <el-drawer title="基础配置"
             size="50%"
             :destroy-on-close="true"
             :model-value="isShow"
             :before-close="handleCancel">
    <div class="step-wrapper">
      <el-steps :active="active">
        <el-step title="进入条件" description="设置流程类型，进入时间以及进入限制"></el-step>
        <el-step title="受众用户" description="筛选进入流程的用户"></el-step>
      </el-steps>
    </div>

    <div>
      <!-- 第一步 -->
      <el-form v-if="active === 0"
               :model="startForm"
               ref="startForm"
               :rules="rules"
               label-width="80px"
               label-position="top"
               :disabled="readOnly">
        <el-form-item label="流程名称" prop="name">
          <el-input
              class="name-input"
              type="text"
              placeholder="请输入流程名称"
              clearable
              v-model.trim="startForm.name"
              maxlength="50"
              show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="流程类型" prop="startType">
          <el-radio-group v-model="startForm.startType">
            <el-radio :label="1" border>单次执行</el-radio>
            <el-radio :label="3" border>周期执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            label="进入时间"
            v-if="startForm.startType !== null || startForm.startType > 0"
        >
          <!-- 单次 -->
          <div v-if="startForm.startType === 1" class="_time flex">
            <span class="time_block">用户在</span>
            <el-form-item prop="publishTime">
              <el-date-picker
                  class="time_block"
                  v-model="startForm.publishTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间"
                  :disabled-date="pickerOptionscreates"
              >
              </el-date-picker>
            </el-form-item>
            <span class="time_block">进入流程，</span>
            <el-form-item prop="invalidTime">
              <el-date-picker
                  class="time_block"
                  v-model="startForm.invalidTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间"
                  :disabled-date="pickerOptionsends"
              >
              </el-date-picker>
            </el-form-item>
            <span class="time_block">停止进入</span>
          </div>

          <!-- 周期 -->
          <div v-if="startForm.startType === 3">
            <div class="_time flex">
              <span class="time_block">在</span>
              <el-form-item prop="publishTime">
                <el-date-picker
                    class="time_block"
                    v-model="startForm.publishTime"
                    type="date"
                    format="YYYY-MM-DD"
                    placeholder="选择日期"
                    :disabled-date="pickerOptionscreates"
                >
                </el-date-picker>
              </el-form-item>
              <span class="time_block"> 至 </span>
              <el-form-item prop="invalidTime">
                <el-date-picker
                    class="time_block"
                    v-model="startForm.invalidTime"
                    type="date"
                    format="YYYY-MM-DD"
                    placeholder="选择日期时间"
                    :disabled-date="pickerOptionsends"
                >
                </el-date-picker>
              </el-form-item>
              <span class="time_block"> 期间内</span>
            </div>
            <div class="_time flex">
              <span class="time_block">用户</span>
              <!-- 月 周 日 -->
              <el-form-item prop="cycleType">
                <el-select
                    class="time_block"
                    v-model="startForm.cycleType"
                    @change="setCycleValueList"
                    placeholder="请选择"
                >
                  <el-option
                      v-for="item in cycleTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- N号 周N -->
              <el-form-item prop="cycleType">
                <el-select
                    v-show="startForm.cycleType !== 3"
                    v-model="startForm.cycleValue"
                    placeholder="请选择"
                    class="time_block"
                >
                  <el-option
                      v-for="item in cycleValueList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 时间点 -->
              <el-form-item prop="cycleDayTime">
                <el-time-picker
                    class="time_block"
                    v-model="startForm.cycleDayTime"
                    format="HH:mm:ss"
                    value-format="HH:mm:ss"
                    :picker-options="{
                      selectableRange: '00:00:00 - 23:59:59',
                    }"
                    placeholder="任意时间点"
                >
                </el-time-picker>
              </el-form-item>

              <span class="time_block">进入流程</span>
            </div>
          </div>
        </el-form-item>

        <div v-if="startForm.startType === 3">
          <el-form-item label="参与限制">
            <el-radio-group v-model="limitCount" @change="handleLimitCountChange">
              <el-radio :label="true" border>限制</el-radio>
              <el-radio :label="false" border>不限制</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
              prop="limitCount"
              v-if="limitCount"
              style="margin-top: 20px"
          >
            <span style="margin-right: 10px">参与</span>
            <el-input-number
                type="number"
                style="margin-right: 10px"
                clearable
                v-model="startForm.limitCount"
                show-word-limit
            >
            </el-input-number>
            <span style="margin-right: 10px">次</span>
          </el-form-item>

        </div>

      </el-form>
      <!-- 第二步 -->
      <el-form
          v-else
          :model="startForm"
          ref="startForm"
          :rules="rules"
          label-width="80px"
          :disabled="readOnly"
      >
        <el-form-item label="选择客群" prop="userGroupId">
          <el-select
              filterable
              collapse-tags
              v-model="startForm.userGroupId"
              @change="setUserGroup"
              placeholder="请选择客群"
          >
            <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择模型">
          <el-select
              filterable
              collapse-tags
              clearable
              v-model="startForm.marketingJourneyInfoId"
              @click.left="setModelList"
              @change="getStrategyl(startForm.marketingJourneyInfoId)"
              placeholder="请选择模型"
          >
            <el-option
                v-for="item in modelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="startForm.marketingJourneyInfoId" label="选择策略" prop="marketingJourneyStrategyId">
          <el-select
              filterable
              collapse-tags
              v-model="startForm.marketingJourneyStrategyId"
              placeholder="请选择策略"
          >
            <el-option
                v-for="item in strategyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="prediction">
          预估<span style="color: #6178ff; margin: 0 4px; font-size: 18px">{{
            startForm.groupNum
          }}</span
        >人
        </div>
        <el-form-item label="执行方式" prop="middleAccessStatus">
          <el-radio-group v-model="startForm.middleAccessStatus">
            <el-radio :label="1" border>只执行当前圈定的用户</el-radio>
            <el-radio :label="0" border>流程进行中新增用户也执行</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="form-footer">
        <el-button style="margin-top: 12px" @click="handleCancel">取消</el-button>
        <el-button v-show="active !== 0"
                   type="primary"
                   style="margin-top: 12px"
                   @click="active--">
          上一步
        </el-button>
        <el-button v-show="active !== 1"
                   type="primary"
                   style="margin-top: 12px"
                   @click="next">
          下一步
        </el-button>
        <el-button v-show="active == 1"
                   type="primary"
                   style="margin-top: 12px"
                   @click="next">
          确定
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import CanvasApi from "@/api/canvasApi";
import {mapMutations} from "vuex";
import {NodeDrawerDataModel} from "@/views/workTable/dataModel/NodeDrawerDataModel";
import {CanvasModel} from "@/views/workTable/dataModel/canvasCreate";

const cycleTypeList = [
  {id: 2, name: "每月"},
  {id: 3, name: "每天"},
  {id: 7, name: "每周"},
]

const weekList = [
  {id: 1, name: '一'},
  {id: 2, name: '二'},
  {id: 3, name: '三'},
  {id: 4, name: '四'},
  {id: 5, name: '五'},
  {id: 6, name: '六'},
  {id: 7, name: '日'},
]

export default {
  props: {
    modelValue: Boolean,
    data: {
      require: false,
      type: Object,
      default: () => ({}),
    },
    addNodeEventData: {
      require: true,
      type: Object,
      default: () => ({}),
    },
    readOnly: Boolean,
  },

  emits: ['cancel', 'confirm', 'confirmModel'],

  data() {
    return {
      cycleTypeList,
      weekList,
      active: 0,
      limitCount: false,
      startForm: {},
      cycleValueList: [],
      monthList: [],
      groupList: [],
      modelList: [], // 模型list
      strategyList: [], // 策略list
      rules: {
        name: [
          {
            required: true,
            message: "请输入流程名称",
            trigger: ["blur"],
          },
        ],
        startType: [
          {
            required: true,
            message: "请选择流程类型",
          },
        ],

        marketingJourneyStrategyId: [
          {
            required: true,
            message: "请选择营销策略",
          },
        ],
        publishTime: [
          {
            required: true,
            message: "请选择日期",
          },
        ],
        invalidTime: [
          {
            required: true,
            message: "请选择日期",
          },
        ],
        cycleDayTime: [
          {
            required: true,
            message: "请选择时间",
          },
        ],
        cycleType: [
          {
            required: true,
            message: "请选择周期类型",
          },
        ],
        cycleValue: [
          {
            required: true,
            message: "请设置周期值",
          },
        ],
        limitCount: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error("参与次数需大于0"));
              }

              callback();
            },
            trigger: "change",
          },
        ],
        userGroupId: [
          {
            required: true,
            trigger: "change",
            message: "请选择客群",
          },
        ],
        middleAccessStatus: [
          {
            required: true,
            trigger: "change",
            message: "请选择执行方式",
          },
        ],
      },
      dialogOpenWay: null, // create || null
    };
  },

  watch: {
    modelValue(newVal) {
      if (newVal) {
        if (this.data.userGroupId) {
          this.startForm = this.recoverStartForm();
          this.userGroupExpectNum()
        } else {
          this.startForm = this.initStartForm()
        }

        this.setMonthList();
        this.setCycleValueList();
        this.remoteMethod("");
        this.getMarketingModel();
        this.handleCreateNode();
      }
    }
  },

  computed: {
    isShow: {
      get(){
        return this.modelValue
      },

      set(val) {
        this.$emit('update:model-value', val)
      }
    }
  },

  methods: {
    ...mapMutations("event", ["setEventProperty", "setEventEvent"]),

    initStartForm() {
      const formInitialValue = {
        name: "",
        userGroupSymbol: "",
        publishTime: "",
        invalidTime: "",
        userGroupId: "",
        startType: 1,
        limitCount: 0,
        cycleType: 2,
        cycleValue: 1,
        cycleDayTime: "",
        middleAccessStatus: 1,
        groupNum: 0,
        marketingJourneyInfoId: "", // 模型id
        marketingJourneyStrategyId: "", // 策略id
      }

      // console.log('init start form', {
      //   ...new CanvasModel().getStructure(),
      //   ...this.data ?? {}, // 从模板新建时会没有数据
      //   ...formInitialValue,
      // })
      return {
        ...new CanvasModel().getStructure(),
        ...this.data ?? {}, // 从模板新建时会没有数据
        ...formInitialValue,
      }
    },

    recoverStartForm() {
      this.limitCount = !!this.data.limitCount
      this.active = 0

      return {...this.data}
    },

    handleLimitCountChange(val) {
      this.limitCount = val
    },

    formValidate() {
      this.$refs.startForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        if (this.active === 0) {
          this.active++;
        } else {
          this.submit();
        }
      });
    },

    pickerOptionscreates(time) {
      // 开始时间的禁用
      if (this.startForm.invalidTime) {
        return (
            time.getTime() > new Date(this.startForm.invalidTime).getTime()
        );
      }
    },

    pickerOptionsends(time) {
      // 结束时间的禁用
      return (
          time.getTime() < new Date(this.startForm.publishTime).getTime()
      );
    },

    setUserGroup() {
      this.groupList.forEach((item) => {
        if (this.startForm.userGroupId == item.id) {
          this.startForm.userGroupSymbol = item.symbol;
        }
      });
      this.userGroupExpectNum();
    },

    // 设置模型可选择列表
    setModelList() {
      this.modelList = this.modelList.filter(item => item.status == 1)
    },

    // 获取营销模型列表
    async getMarketingModel() {
      let param = {
        currentPage: 1,
        showCount: -1,
      };
      let rs = await CanvasApi.getMarketingModel(param);

      // console.log("getMarketingModel-rs", rs);
      if (rs.code === 200) {
        this.modelList = rs.payload;
        if (this.startForm.marketingJourneyInfoId) {
          this.getStrategyl(this.startForm.marketingJourneyInfoId, true);
        }
      }
    },

    //  获取营销模型下的策略
    async getStrategyl(id, isEdit) {
      if (!isEdit) {
        this.startForm.marketingJourneyStrategyId = "";
      }
      let param = {
        currentPage: 1,
        showCount: -1,
        id: id,
      };
      let rs = await CanvasApi.getStrategyl(param);

      // console.log("getMarketingModel-rs", rs);
      if (rs.code === 200) {
        this.strategyList = rs.payload;
      }
    },

    async remoteMethod(query) {
      let param = {
        name: query,
        currentPage: 1,
        showCount: -1,
      };
      let rs = await CanvasApi.getUserGroupList(param);
      if (rs.code === 200) {
        this.groupList = rs.payload;
      }
    },

    submit() {
      this.limitCount == 0 ? (this.startForm.limitCount = 0) : "";
      this.startForm.publishTime = new Date(this.startForm.publishTime).getTime();
      this.startForm.invalidTime = new Date(this.startForm.invalidTime).getTime();
      // console.log('[ this.startForm ] >', this.startForm)
      this.$emit("confirm", new NodeDrawerDataModel({
        dialogData: this.startForm,
        validateResult: {
          result: true
        }
      }));

      this.$emit("confirmModel", {
        marketingJourneyInfoId: this.startForm.marketingJourneyInfoId, // 模型id
        marketingJourneyStrategyId: this.startForm.marketingJourneyStrategyId,
      })

      this.closeStart();
    },
    // 获取预估人数
    async userGroupExpectNum() {
      let rs = await CanvasApi.userGroupExpectNum({
        userGroupId: this.startForm.userGroupId,
      });

      if (rs.code === 200) {
        this.startForm.groupNum = rs.payload;
      }
    },
    closeStart() {
      this.$emit("cancel");
    },

    handleCancel() {
      this.closeStart();
    },

    next() {
      this.formValidate();
    },

    setCycleValueList() {
      // console.log("[ this.startForm.cycleType ] >", this.startForm.cycleType);
      if (this.startForm.cycleType == 2) {
        this.cycleValueList = this.monthList;
      } else if (this.startForm.cycleType == 7) {
        this.cycleValueList = this.weekList;
      }
      this.startForm.cycleValue = 1;
    },
    // 初始化月
    setMonthList() {
      let monthList = [];
      let time = 31;
      for (let index = 1; index <= time; index++) {
        monthList.push({id: index, name: `${index}号`});
      }
      this.monthList = monthList;
    },

    handleCreateNode() {
      const {cell} = this.addNodeEventData;
      this.dialogOpenWay = cell.getData().dialogOpenWay; // create | null 对话框的打开方式
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-drawer) {
  padding: 0 20px;
  line-height: 1;
  min-width: 1000px;
}

._time {
  //._title {
  //  padding-right: 15px;
  //}

  .time_block {
    margin: 0 10px;
    word-break: keep-all;
  }
}

.flex {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-footer {
  position: absolute;
  right: 40px;
  bottom: 40px;
}

.el-input {
  width: 240px;
}

.step-wrapper {
  width: 450px;
  position: relative;
  margin: 35px auto;
}

.prediction {
  width: 438px;
  height: 45px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 2px;
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 24px;
  font-size: 14px;
  color: #2c313b;
}

:deep(.el-step.is-horizontal .el-step__line) {
  height: 0px;
  top: 15px;
  left: 0;
  right: 0;
  border: 1px dashed #7f8288;
  background-color: #fff;
  margin: 0 20px 0 52px;
}

:deep(.el-step__icon) {
  width: 32px;
  height: 32px;
}

:deep(.el-step__line-inner) {
  border-style: none;
}

:deep(.el-input-number__increase), :deep(.el-input-number__decrease) {
  bottom: 2px;
}

.name-input {
  width: 520px; // 520改的宽度就给520吧
}
</style>
